🔥 Design Patterns Used in ASP.NET Core Middleware

 

🔥 Design Patterns Used in ASP.NET Core Middleware (Deep Dive)

First: What is Middleware? (1-line)

Middleware is a component that handles HTTP requests and responses in a pipeline.

Every request passes through middleware components one by one.


🔗 1️⃣ Chain of Responsibility Pattern (MOST IMPORTANT)

✔ Where used

👉 Middleware pipeline

✔ Why useful

  • Each middleware decides:

    • Handle request

    • Pass to next middleware

  • No tight coupling


📌 How the pipeline works

Request ↓ Exception Middleware ↓ Authentication Middleware ↓ Authorization Middleware ↓ Endpoint Middleware ↓ Response

Each middleware has a chance to act.


📌 Example Middleware

app.Use(async (context, next) => { Console.WriteLine("Before Request"); await next(); // Pass to next middleware Console.WriteLine("After Response"); });

✔ If next() is not called → request stops
✔ This is Chain of Responsibility


🗣 Interview Line

“ASP.NET Core middleware pipeline follows the Chain of Responsibility pattern, where each middleware decides whether to handle the request or pass it to the next component.”


🎨 2️⃣ Decorator Pattern

✔ Where used

👉 Middleware wraps the next middleware

✔ Why useful

  • Add behavior before and after

  • No change to original logic


📌 Visual understanding

Logging └── Authentication └── Authorization └── Endpoint

Each middleware decorates the next.


📌 Example

app.Use(async (context, next) => { // Before Console.WriteLine("Logging Request"); await next(); // call inner middleware // After Console.WriteLine("Logging Response"); });

✔ Adds logging
✔ Does NOT modify next middleware


🗣 Interview Line

“Middleware uses the Decorator pattern because each middleware adds behavior around the next one without changing it.”


🧩 3️⃣ Adapter Pattern

✔ Where used

👉 Adapting raw HTTP to ASP.NET Core objects

✔ Why useful

  • Converts:

    • Kestrel HTTP request → HttpContext

    • Legacy systems → modern pipeline


📌 Example

public class MyMiddleware { private readonly RequestDelegate _next; public MyMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { // HttpContext is an abstraction over raw HTTP await _next(context); } }

HttpContext adapts low-level HTTP details


🗣 Interview Line

“ASP.NET Core middleware adapts low-level HTTP requests into a unified HttpContext using the Adapter pattern.”


🔀 4️⃣ Strategy Pattern

✔ Where used

👉 Authentication & Authorization middleware

✔ Why useful

  • Choose algorithm at runtime

  • JWT, Cookies, OAuth, API Key


📌 Example

builder.Services.AddAuthentication() .AddJwtBearer() .AddCookie();

At runtime, ASP.NET Core selects one strategy based on request.


🗣 Interview Line

“Authentication in ASP.NET Core uses the Strategy pattern to dynamically choose JWT, Cookie, or OAuth authentication.”


👀 5️⃣ Observer Pattern

✔ Where used

👉 Logging & Diagnostics

✔ Why useful

  • One event → many listeners

  • Loose coupling


📌 Example

logger.LogInformation("User logged in");

Multiple listeners receive this:

  • Console

  • Application Insights

  • File logs


🗣 Interview Line

“Logging in ASP.NET Core follows the Observer pattern, where multiple log providers subscribe to log events.”


🧠 6️⃣ Factory Pattern (Bonus)

✔ Where used

👉 Middleware creation

✔ Example

app.UseMiddleware<MyCustomMiddleware>();

ASP.NET Core internally uses a Factory to:

  • Create middleware

  • Inject dependencies


🗣 Interview Line

“ASP.NET Core internally uses the Factory pattern to create middleware instances and inject dependencies.”


🎯 One-Screen Summary (Memorize This)

PatternUsed WherePurpose
Chain of ResponsibilityMiddleware pipelinePass request through handlers
DecoratorMiddleware wrappingAdd behavior before/after
AdapterHttpContext abstractionConvert raw HTTP
StrategyAuthentication/AuthorizationChoose algorithm
ObserverLogging, diagnosticsNotify multiple listeners
FactoryMiddleware creationCentralized creation

🏆 Perfect Final Interview Answer

“ASP.NET Core middleware heavily uses design patterns. The pipeline follows Chain of Responsibility, each middleware decorates the next one using the Decorator pattern. HttpContext acts as an Adapter over raw HTTP. Authentication uses Strategy pattern, logging uses Observer pattern, and middleware instances are created using Factory pattern.”

Comments

Popular posts from this blog

.NET Core Interview Questions and Answers for 10+ Years Experienced Professionals

What are SOLID Principles?

.NET Core Senior Interview Q&A